import requests  
import os  
from typing import Optional  
  
def upload_file_to_dify(  
    file_path: str,  
    api_key: str="app-onsocHdNfaevtAxQAm3gbz3T",  
    user_id: str="ai_demo_user",  
    api_base_url: str = "http://127.0.0.1:8090/v1"  
) -> dict:  
    """  
    上传文件到Dify并获取文件ID  
      
    Args:  
        file_path: 本地文件路径  
        api_key: Dify API密钥  
        user_id: 用户标识符（自定义）  
        api_base_url: API基础URL  
      
    Returns:  
        包含文件信息的字典，包括文件ID  
    """  
      
    # 检查文件是否存在  
    if not os.path.exists(file_path):  
        raise FileNotFoundError(f"文件不存在: {file_path}")  
      
    # 准备请求URL和头部  
    url = f"{api_base_url}/files/upload"  
    headers = {  
        'Authorization': f'Bearer {api_key}'  
    }  
      
    # 准备文件和数据  
    with open(file_path, 'rb') as file:  
        files = {  
            'file': (os.path.basename(file_path), file, 'pdf')  
        }  
        data = {  
            'user': user_id  
        }  
          
        # 发送请求  
        response = requests.post(url, headers=headers, files=files, data=data)  
      
    # 检查响应状态  
    if response.status_code == 201:  
        return response.json()  
    else:  
        raise Exception(f"上传失败: {response.status_code} - {response.text}")  
    
if __name__ == "__main__":
    # 示例用法
    try:
        # 定义文件的相对路径
        relative_path = os.path.join("settlement_pdfs", "结算单_北京四季酒店_20250605162736.pdf")

        # 获取文件的绝对路径
        absolute_path = os.path.abspath(relative_path)
        
        print("准备上传文件:", absolute_path)
        response = upload_file_to_dify(absolute_path)
        print("文件上传成功:", response)
    except Exception as e:
        print("上传失败:", str(e))